iT邦幫忙

13

📅 自動發送 Google Calendar 事件到 LINE:我實作的早晨提醒系統

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20250726/20155103ScPjtMqtKo.png

📲 申請 LINE Messaging API

申請 LINE Message Bot 並取得 access token,可參考以下文章說明:
👉 LINE Messaging API 註冊申請


🔧 我的需求:只要「今天的事件」就好

我想要一個簡單的功能:每天早上收到 LINE 通知,提醒我今天有哪些行事曆事件。

一開始的程式邏輯還包含「建立行事曆事件」的部分,但對我來說用不到。於是我請 ChatGPT 協助我簡化,只留下「讀取事件」與「發送 LINE 通知」兩個功能。

這是我後來使用的主要功能流程:

  • ✅ 抓取今天的所有事件
  • ✅ 整理為簡潔訊息格式(主旨+時間)
  • ✅ 傳送至 LINE

📌 我的行事曆不只一個,會抓到全部嗎?

我平常不只使用「主要行事曆」,還有像是「家庭」、「朋友」等與他人共用的日曆,最一開始的程式只能抓 getDefaultCalendar(),但那只抓得到主行事曆。

於是我改用 getAllCalendars(),可以抓到我帳號有權限的所有日曆,包括共用日曆與 Google Classroom 行事曆。

如果妳也想抓全部的行事曆事件,這段程式碼會是好用的起點。


🧱 最後使用的完整程式碼

const LINE_CHANNEL_ACCESS_TOKEN = '...';
const USER_ID = '...';

function sendTodayEventsToLine() {
  const allCalendars = CalendarApp.getAllCalendars();
  const today = new Date();
  const start = new Date(today.setHours(0, 0, 0, 0));
  const end = new Date(today.setHours(23, 59, 59, 999));
  const allEvents = [];

  allCalendars.forEach(calendar => {
    const events = calendar.getEvents(start, end);
    events.forEach(e => {
      allEvents.push({
        calendarName: calendar.getName(),
        title: e.getTitle(),
        startTime: Utilities.formatDate(e.getStartTime(), Session.getScriptTimeZone(), "HH:mm"),
        endTime: Utilities.formatDate(e.getEndTime(), Session.getScriptTimeZone(), "HH:mm")
      });
    });
  });

  if (allEvents.length === 0) {
    sendLineMessage("📅 今天沒有排定的行事曆事件", LINE_CHANNEL_ACCESS_TOKEN, USER_ID);
    return;
  }

  const lines = allEvents.map(e =>
    `📌【${e.calendarName}】${e.title}(${e.startTime} - ${e.endTime})`
  );

  const message = `📅 今天所有行事曆的事件(共 ${allEvents.length} 筆):\n\n${lines.join("\n")}`;
  sendLineMessage(message, LINE_CHANNEL_ACCESS_TOKEN, USER_ID);
}

function sendLineMessage(message, token, userId) {
  const url = "https://api.line.me/v2/bot/message/push";
  const payload = {
    to: userId,
    messages: [{ type: "text", text: message }]
  };

  const options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(payload),
    headers: { Authorization: "Bearer " + token }
  };

  UrlFetchApp.fetch(url, options);
}

⏰ 建議搭配時間觸發器使用

可以在 Apps Script 的「觸發器」設定每天 08:00 執行 sendTodayEventsToLine(),自動推播提醒,讓一天從清楚的行程開始。


🤖 適合問 GPT 的 prompt

如果妳也想試著用 GPT 幫忙撰寫 Apps Script,可以這樣問:

請幫我寫一段 Google Apps Script,抓取我今天所有行事曆的事件,並用 LINE Messaging API 發送訊息。

進階功能也能詢問:

請幫我修改這段程式碼,只抓「家庭」與「朋友」行事曆的事件,並附上事件地點。


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

1
eleanor018
iT邦新手 5 級 ‧ 2025-08-18 21:12:52

感謝分享~我超需要!/images/emoticon/emoticon07.gif

0
lulu2570
iT邦新手 5 級 ‧ 2025-08-19 19:18:56

好讚的分享! 非常適合每天一起床就打開line查看訊息的人

我要留言

立即登入留言